﻿using lxm.download.app.Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace lxm.download.app
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void btnChoosePath_Click(object sender, EventArgs e)
        {

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择保存路径";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }

                this.txtBoxSavePath.Text = dialog.SelectedPath;
            }
        }


        private void BtnChooseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请导入图片文件";
            dialog.Filter = "(表格文件)*.xls;*.xlsx;|*.xls;*.xlsx;";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtBoxLoadFile.Text = dialog.FileName;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtBoxSavePath.Text))
            {
                MessageBox.Show(this, "请选择保存路径", "提示");
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtBoxLoadFile.Text))
            {
                MessageBox.Show(this, "请先导入图片文件", "提示");
                return;
            }
            btnSave.Enabled = false;
            btnSave.Text = "下载中.....";
            try
            {
                if (!Directory.Exists(this.txtBoxSavePath.Text))
                {
                    Directory.CreateDirectory(this.txtBoxSavePath.Text);
                }


                var clist = ReadFromExcelFile(this.txtBoxLoadFile.Text);

                //开十个线程一起下载
                if (!clist.Any())
                {
                    MessageBox.Show(this, "表格的数据不能为空", "提示");
                    return;
                }

                labelProgress.Text = $"进度：0/{clist.Count()}";

                progressBar1.Maximum = clist.Count();

                var pageSize = 10;
                var count = clist.Count();

                var pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;

                for (int i = 0; i < pageCount; i++)
                {

                    clist.Skip(i * pageSize).Take(pageSize).AsParallel().ForAll((item) => {
                    //clist.Skip(i * pageSize).Take(pageSize).ToList().ForEach((item) => {

                        var path = Path.Combine(this.txtBoxSavePath.Text, item.GetSaveFileName());

                            if (!File.Exists(path))
                            {
                                DownloadFile(item.DownLoadUrl, path);
                            }
                    });

                    if (i == pageCount - 1)
                    {
                        labelProgress.Text = $"进度：{count}/{count}";
                        progressBar1.Value = count;
                    }
                    else
                    {
                        labelProgress.Text = $"进度：{(i + 1) * pageSize}/{count}";
                        progressBar1.Value = (i + 1) * pageSize;
                    }
                }

                btnSave.Enabled = true;
                btnSave.Text = "开始下载";

                MessageBox.Show(this, $"下载完成", "提示");
            }
            
            catch (AggregateException ex)
            {
                btnSave.Enabled = true;
                btnSave.Text = "开始下载";
                MessageBox.Show(this, $"下载失败:{ex.Message}", "提示");
                return;
            }
            catch (Exception ex)
            {
                btnSave.Enabled = true;
                btnSave.Text = "开始下载";
                MessageBox.Show(this, $"下载失败:{ex.Message}", "提示");
                return;
            }
        }


        public List<PictureModel> ReadFromExcelFile(string filePath)
        {
            IWorkbook wk = null;
            var list = new List<PictureModel>();

            string extension = System.IO.Path.GetExtension(filePath);
            try
            {
                FileStream fs = File.OpenRead(filePath);
                if (extension.Equals(".xls"))
                {
                    //把xls文件中的数据写入wk中
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //把xlsx文件中的数据写入wk中
                    wk = new XSSFWorkbook(fs);
                }

                fs.Close();
                //读取当前表数据
                ISheet sheet = wk.GetSheetAt(0);

                IRow row = sheet.GetRow(0);  //读取当前行数据
                                             //LastRowNum 是当前表的总行数-1（注意）
                int offset = 0;


                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    row = sheet.GetRow(i);  //读取当前行数据
                    if (!string.IsNullOrWhiteSpace(row.GetCell(0).ToString()))
                    {

                        var pi = new PictureModel()
                        {
                            DownLoadUrl = row.GetCell(0).ToString(),
                            UserName = row.GetCell(1).ToString(),
                            Phone = row.GetCell(2).ToString(),
                            Time = row.GetCell(3).ToString(),
                            Day = row.GetCell(4).ToString(),
                        };
                        list.Add(pi);
                    }
                }
            }

            catch (Exception e)
            {
                throw e;
            }
            return list;
        }

        /// <summary>
        /// 下载文件(显示进度)
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="filename"></param>
        /// <param name="prog"></param>
        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog = null)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception ex)
            {

            }
        }
    }
}